package com.core.bean;

import com.core.dao.jdbcmysql.CarItemDao;

import java.util.ArrayList;
import java.util.List;

public abstract class ShoppingCar {
    private static List<CarItem> items;

    static {
        try {
            items = new CarItemDao().queryList();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public abstract void save(User user, String shopId) throws Exception;

    public void save(User user, String shopId,String goodsId, int count) throws Exception {

    }

    public void add(Goods goods, int count, String remark) {
        CarItem item = findItem(goods);
        if (item == null)
            item = new CarItem();
        item.setGoods(goods);
        item.setCount(item.getCount() + count);
        item.setRemark(remark);
    }

    public void add(Goods goods, int count) {
        CarItem item = findItem(goods);
        if (item == null) {
            item = new CarItem();
            item.setGoods(goods);
            item.setCount(count);
        }
        item.setGoods(goods);
        item.setCount(item.getCount() + count);

    }

    public void add(Goods goods) {
        CarItem item = findItem(goods);
        if (item == null)
            item = new CarItem();
        item.setGoods(goods);
        item.setCount(item.getCount() + 1);
    }

    public void remove(Goods goods) {
        CarItem item = findItem(goods);
        items.remove(item);
    }

    public void remove(Goods goods, int count) throws Exception {
        CarItem item = findItem(goods);
        if (item == null)
            return;
        if (count >= item.getCount() && count < 0)
            throw new Exception("");
        item.setCount(item.getCount() - count);
    }

    private CarItem findItem(Goods goods) {
        for (CarItem item : items) {
            if (item.getGoods().equals(goods)) {
                return item;
            }
        }
        return null;
    }

    public List<CarItem> getItems() {
        return this.items;
    }
}
